package com.example.factory.kitchen;

import lombok.AllArgsConstructor;

import java.util.LinkedList;
import java.util.List;

/**
 * 截断式： 结点控制下移方式。
 * 1. 通过结点传入整个链条进行持有 「chain」。2. 通过 StepChain -> entry 控制链条的结尾和下移。3. 通过结点调用 「chain」触发 2
 */
public class ChainOfKitchen {
    public static void main(String[] args) {
        StepChain stepChain = new StepChain();
        stepChain.addFilter(new MakeFireStep()).addFilter(new WashVegetablesStep());
        stepChain.entry(new Request("wash"),new Response("base response"));

    }
}

interface Step {
    boolean entry(Request request, Response response, StepChain chain);
}

class StepChain {
    List<Step> stepChain = new LinkedList<>();
    int index = 0;

    StepChain addFilter(Step step) {
        stepChain.add(step);
        return this;
    }

    public boolean entry(Request request, Response response) {
        if(index == this.stepChain.size())return false;
        Step step = this.stepChain.get(index++);
        if(step !=null)
            step.entry(request, response, this);
        return true;
    }
}

class MakeFireStep implements Step {

    @Override
    public boolean entry(Request request, Response response, StepChain chain) {
        if("fire".equals(request.msg)){
            System.out.println(request.msg + " MakeFireStep");
        }else{
            chain.entry(request, response);
        }
        return true;
    }
}

class WashVegetablesStep implements Step {

    @Override
    public boolean entry(Request request, Response response, StepChain chain) {
        if("wash".equals(request.msg)){
            System.out.println(request.msg + " WashVegetablesStep");
        }else{
            chain.entry(request, response);
        }
        return true;
    }
}

@AllArgsConstructor
class Request {
    String msg;
}

@AllArgsConstructor
class Response {
    String msg;
}